package util.publish;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TagMake {

	/**
	 * 使用前需要配置tag-slug的名字，tag-slug统一使用一个关键词+流水号的形式
	 */
	public void tagProduce() {
		
		//final String tagNameStr = "study-abroad";
		final int bankForSort = 20;
		Connection conn = null;
		Statement stmt = null;
		Statement stmtAdd = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager
					.getConnection("jdbc:mysql://" + host + "/" + dBName + "?user=root");
			stmt = conn.createStatement();
			stmtAdd = conn.createStatement();
			rs = stmt.executeQuery("select max(term_taxonomy_id) from wp_term_taxonomy");
			rs.next();
			int term_taxonomy_id = rs.getInt(1) + 1;
			if(term_taxonomy_id==1){
				term_taxonomy_id = term_taxonomy_id + bankForSort;
			}
			rs = stmt.executeQuery("select max(term_id) from wp_term_taxonomy");
			rs.next();
			int term_id = rs.getInt(1) + 1;
			if(term_id==1){
				term_id = term_id + bankForSort;
			}
			rs = stmt.executeQuery("SELECT keyword,kwEng,id FROM keywords where tagIs = 0");
			while (rs.next()) {
				//slug字段是写成了 关键字的utf-8转码
				String sql = "insert into wp_terms (term_id,name,slug) values (" + term_id + ",'" + rs.getString("keyword") + "','" + URLEncoder.encode(rs.getString("keyword"), "UTF-8") + "')";
				String sql2 = "insert into wp_term_taxonomy (term_taxonomy_id,term_id,taxonomy,description) values (" + term_taxonomy_id + "," + term_id + ",'post_tag','" + rs.getString("keyword") + "')";
				stmtAdd.execute(sql);
				stmtAdd.execute(sql2);
				stmtAdd.execute("update keywords set tagIs = 1 where id = " + rs.getInt("id"));
				term_id++;
				term_taxonomy_id++;
				System.out.println("生成新tag" + rs.getString("keyword") + rs.getInt("id") + "-----" + dBName);
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException ex) {
			// handle any errors
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) {
					rs.close();
					rs = null;
				}
				if(stmt != null) {
					stmt.close();
					stmt = null;
				}
				if(conn != null) {
					conn.close();
					conn = null;
				}
				if(stmtAdd != null) {
					stmtAdd.close();
					stmtAdd = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	String dBName = null;
	String host = null;
	public void setDBName(String dBName) {
		this.dBName = dBName;
	}
	public void setHost(String host) {
		this.host = host;
	}
}
